package com.laolang.pluto.framework.config.security.filter;

import com.laolang.pluto.common.util.SecurityUtil;
import com.laolang.pluto.framework.config.security.pojo.LoginUser;
import com.laolang.pluto.framework.config.security.service.TokenService;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * @author laolang
 * @date 2021-08-07 03:34
 */
@RequiredArgsConstructor
@Component
public class JwtFilter extends OncePerRequestFilter {

    private final TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (null != loginUser && null == SecurityUtil.getAuthentication()) {
            tokenService.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginUser, null,
                    loginUser.getAuthorities());
            token.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(token);
        }
        filterChain.doFilter(request, response);
    }
}
